package com.roy.workbench.bookmark.controller.v1;


import com.roy.workbench.bookmark.domain.Bookmark;
import com.roy.workbench.bookmark.service.BookmarkService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.util.Date;

/**
 * Created by elloxxn on 12/6/2017.
 */
@RestController
@RequestMapping("/v1/bookmarks")
public class BookmarkControllerV1 {

    @Autowired
    private BookmarkService bookmarkService;

    @GetMapping
    public ResponseEntity<Page<Bookmark>> find() {
        PageRequest pageRequest = new PageRequest(0,20);

        Page<Bookmark> page = bookmarkService.query(pageRequest);
        if (CollectionUtils.isEmpty(page.getContent()))
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        return new ResponseEntity(page, HttpStatus.OK);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Bookmark> findById(@PathVariable("id") Long id) {
        Bookmark one = bookmarkService.findById(id);
        return new ResponseEntity(one, HttpStatus.OK);
    }

    @PostMapping
    public ResponseEntity<Bookmark> create(@RequestBody Bookmark bookmark){
        bookmark.setCreateTime(new Date());
        bookmark.setUpdateTime(new Date());
        Bookmark bookmark1 = bookmarkService.save(bookmark);

        return new ResponseEntity(bookmark1, HttpStatus.CREATED);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Bookmark> deleteById(@PathVariable("id") Long id) {
        Bookmark one = null;
        try {
            one = bookmarkService.delete(id, true);
        } catch (Exception e) {
            return new ResponseEntity(null, HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity(one, HttpStatus.OK);
    }
}
